<template>
  <div></div>
</template>
<script>
import storage from "store";
import appConfig from "@/config/appConfig";
import apiService from "@/api/apiService";
// import { getCurrentUser } from "@/utils";
import wx from "weixin-js-sdk";
export default {
  name: "WechatAuth",
  data() {
    return {
      code: "",
      state: "",
      path: "",
      unionid: "",
      token: "",
      qrCodeDataURL: "",
      go: "",
      goParam: "",
    };
  },
  mounted() {
    // this.$nextTick(()=>{
    //重定向到该页面之后会拿到code，并通过code获取用户unionId，进而实现登录，拿到用户token
    const query = this.$route.query
    this.code = query.code;
    this.state = query.state;
    this.go = query.go || "/home";
    this.goParam = query.goParam;
    if (this.code !== "" && this.code !== undefined) {
      apiService
        .post("/wxLogin", {
          code: this.code,
          loginAuth: this.goParam,
        })
        .then((res) => {
          // this.token = res.data.token
          if (res.code === 0) {
            storage.set(
              appConfig.ACCESS_TOKEN_NAME,
              res.data,
              7 * 24 * 60 * 60 * 1000
            );
            // getCurrentUser()
            if (this.go) {
              if (this.go === "LoginAuthorize") {
                wx.closeWindow();
                return;
              }
              if (this.goParam) {
                // 将查询参数对象转换为查询参数字符串
                const queryString = new URLSearchParams(query).toString();
                location.replace(`${this.go}?${queryString}`);
              } else {
                location.replace(this.go);
              }
            } else {
              location.replace(this.go);
            }
          } else {
            location.replace(this.go);
          }
        });
    } else {
      //关闭wechatAuth, 避免出现空白页
      this.$store.dispatch("tagsView/delView", this.$route);
      this.authorize();
      // this.$router.replace(this.go)
    }
  },
  methods: {
    authorize() {
      this.$axiosSecondary
        .get("/generateWxloginUrl?go=" + this.go)
        .then((res) => {
          const authorizationUrl = res.data;
          window.location.replace(authorizationUrl);
        });
    },
  },
};
</script>

<style></style>
